package com.firefly.admin.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.firefly.admin.common.constant.Constants;
import com.firefly.admin.common.properties.DruidProperties;
import com.firefly.admin.common.utils.Sm2Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;

import javax.sql.DataSource;

/**
 * @author hejishan
 */
@Configuration
public class DruidConfiguration {
    @Autowired
    private DruidProperties druidProperties;

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid() {
        return new DruidDataSource();
    }

    @Bean
    public ServletRegistrationBean<StatViewServlet> DruidStatViewServle() {
        ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //白名单：
        servletRegistrationBean.addInitParameter(Constants.Druid.ALLOW, druidProperties.getAllow());
        //IP黑名单 (存在共同时，deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
        servletRegistrationBean.addInitParameter(Constants.Druid.DENY, druidProperties.getDeny());
        //登录查看信息的账号密码.
        servletRegistrationBean.addInitParameter(Constants.Druid.LOGIN_USER_NAME, Sm2Util.decryptData(druidProperties.getLoginUsername()));
        servletRegistrationBean.addInitParameter(Constants.Druid.LOGIN_PASSWORD, Sm2Util.decryptData(druidProperties.getLoginPassword()));
        //是否能够重置数据.
        servletRegistrationBean.addInitParameter(Constants.Druid.RESET_ENABLE, druidProperties.getResetEnable());
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean<WebStatFilter> druidStatFilter() {
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>(new WebStatFilter());
        //添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
        //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    @Bean
    PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
        return new PersistenceExceptionTranslationPostProcessor();
    }
}
